"""
异常处理
"""

try:
    f = open("D:/test3.txt","r",encoding="utf-8")
except:
    print("文件不存在")

# 捕获特定异常
try:
    f = open("D:/test3.txt", "r", encoding="utf-8")
except FileNotFoundError as e:
    print(e)

# 捕获所有异常
try:
    f = open("D:/test3.txt", "r", encoding="utf-8")
except Exception as e:
    print(e)

# 捕获多个异常
try:
    i = 1 / 0
    f = open("D:/test3.txt", "r", encoding="utf-8")
except (FileNotFoundError,ZeroDivisionError) as e:
    print(e)


# 异常else
try:
    print(num) # 未定义，报错
except (NameError, ZeroDivisionError) as e:
    print(e) # 打印 name 'num' is not defined
else:
    print("无异常") # 有异常，不执行

num = None
try:
    print(num) # 不报错
except (NameError, ZeroDivisionError) as e:
    print(e) # 打印 name 'num' is not defined
else:
    print("无异常") # 执行 无异常

# 异常finally
global f1
try:
    f1 = open("C:/code/aaa.txt", "r")
except Exception as e:
    print(e)
finally:
    f1.close() # 一定会执行close操作

